from rest_framework.viewsets import ModelViewSet

from oauth2_provider.contrib.rest_framework import TokenHasScope

from prj005.permissions import MainPermissions
from prj005.utils.constants import SESSION_DATA
from prj005.models.info import Info
from functools import reduce
from operator import and_

from django.db.models import Q


class MainSameView(ModelViewSet):
    permission_classes = [TokenHasScope, MainPermissions]
    required_scopes = ['prj005']

    def get_queryset(self):
        user = self.request.user
        if hasattr(self, 'set_session_data') and getattr(self, 'set_session_data'):
            SESSION_DATA['{}'.format(user.id)] = None

        if user.has_perm('prj005.prj005_all_permissions'):
            return super().get_queryset()

        return self.queryset.filter(owner=user)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class SearchInfoView(MainSameView):

    def search_instances(self, request_data):
        search_query = []

        for k, v in request_data.items():
            if not v:
                continue

            if hasattr(Info, k) or k.startswith('owner'):
                query = '__'.join([k, 'icontains'])
                search_query.append(Q(**{query: v}))

        if search_query:
            srearch_queryset = super().get_queryset().filter(reduce(and_, search_query))
        else:
            srearch_queryset = super().get_queryset()

        return srearch_queryset
